package com.hmall.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器： 拦截所有的请求
 * 场景： 统一鉴权
 * 实现GatewayFilter, Ordered接口
 */
//@Component
public class DemoGlobalFilter implements GlobalFilter, Ordered {

    //Mono<Void> 响应式流： 一个字一个字响应的
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求与响应对象 HttpServletRequest, 网关对请求对象进行了封装
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求路径
        System.out.println("request.getURI().getPath() = " + request.getURI().getPath());
        // 获取请求头
        String header = request.getHeaders().getFirst("User-Agent");
        System.out.println("header = " + header);
        // 响应401
        response.setRawStatusCode(401);
        return response.setComplete();// setComplete请求完成了，到些为此
        //放行
        //return chain.filter(exchange);
    }

    @Override
    // 执行的顺序，越小越先执行
    public int getOrder() {
        return 0;
    }
}
